/**
 * Created by cxl on 2017/7/18.
 */
var Player = require('./player').Player;

// 玩家管理器
function GroupManager() {
    this.groupMember = {
        /***
         * "gid" : [uid,uid]
         */
    };
    this.applyJoin = {
        /***
         * "gid" : [uid,uid]
         */
    };
}


GroupManager.prototype = {
    // 初始化
    init: function (callback) {
        // 加载平台数据
        var cursor = DB.user.find();
        cursor.each(function (err, item) {
            if (err) {
                callback && callback(err);
                return;
            }

            if (item) {
                var groups = item.groups;
                if (groups != null) {
                    for (var i = 0, len = groups.length; i < len; i++) {
                        var groupId = groups[i];
                        if (!this.groupMember.hasOwnProperty(groupId)) {
                            this.groupMember[groupId] = [];
                            this.groupMember[groupId].push(groupId);
                            this.agreeJoin(groupId, groupId, function (err, p) {});
                        } else {
                            this.groupMember[groupId].push(item._id);
                        }
                    }
                }
            }

            if (cursor.isClosed()) {
                callback && callback();
            }
        }.bind(this));
    },

    /***
     * 申请加入群组
     * @param gid
     * @param uid
     * @param cb
     */
    applyJoinGroup: function (gid, uid, cb) {
        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                cb(Code.GROUP_INVALID);
                return;
            }
            var groups = player.user.groups;
            if (groups) {
                if (this.hasMember(groups, gid)) {
                    cb(Code.IS_MEMBER_OF_GROUP);
                    return;
                }
            }
        }.bind(this));
        gPlayerManger.getPlayer(gid, function (player) {
            if (!player) {
                cb(Code.GROUP_INVALID);
                return;
            }
            if (!this.applyJoin.hasOwnProperty(gid)) {
                this.applyJoin[gid] = [];
            }
            var arr = this.applyJoin[gid];
            if (this.hasMember(arr, uid)) {
                cb(Code.REPEAT_APPLY);
                return;
            }
            this.applyJoin[gid].push(uid);
            gPlayerManger.getPlayer(uid, function (p) {
                player.send("onHasApplyJoin", {"applyPlayer": p});
            });
            cb();
        }.bind(this));
    },

    /***
     * 添加会员到指定群组
     * @param uid
     * @param cb
     */
    agreeJoin: function (gid, uid, cb) {
        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                cb(Code.DB_ERROR);
                return;
            }
            if (!player.user.groups) {
                player.user.groups = [];
            }
            for (var i = 0; i < player.user.groups.length; i++) {
                if (player.user.groups[i] == gid) {
                    this.delApply(gid, uid, function (err, info) {
                    });
                    cb(Code.REPEAT_JOIN);
                    return;
                }
            }
            player.user.groups.push(gid);
            player.markDirty("groups");
            player.save(true);
            if (!this.groupMember.hasOwnProperty(gid)) {
                this.groupMember[gid] = [];
                this.groupMember[gid].push(gid);
                this.agreeJoin(gid, gid, function (err, p) {
                });
                // gPlayerManger.getPlayer(gid,function(p){
                //     if (!p) {
                //         cb(Code.DB_ERROR);
                //         return;
                //     }
                //     if (!p.user.groups) {
                //         p.user.groups = [];
                //     }
                //     for (var i = 0; i < p.user.groups.length; i++) {
                //         if (p.user.groups[i] == gid) {
                //             this.delApply(gid, uid, function (err, info) {
                //             });
                //             cb(Code.REPEAT_JOIN);
                //             return;
                //         }
                //     }
                //     p.user.groups.push(gid);
                //     p.markDirty("groups");
                //     p.save(true);
                // });
                this.groupMember[gid].push(uid);
            } else {
                var groups = this.groupMember[gid];
                if (groups) {
                    if (this.hasMember(groups, uid)) {
                        cb(Code.REPEAT_JOIN);
                        return;
                    }
                    groups.push(uid);
                }
            }
            this.delApply(gid, uid, function (err, info) {
            });
            cb(null, player);
        }.bind(this));
    },

    /***
     * 通过群组id获取组中所有的会员
     * @param gid
     * @param cb
     */
    getMembersOfGroup: function (gid, cb) {
        if (this.groupMember.hasOwnProperty(gid)) {
            var group = this.groupMember[gid];
            var result = [];
            for (var i = 0; i < group.length; i++) {
                gPlayerManger.getPlayer(group[i], function (p) {
                    if (!p) {
                        return;
                    }
                    result.push(p);
                });
            }
            cb(result);
        } else {
            cb(Code.GROUP_INVALID);
        }
    },

    /***
     * 获取申请指定组的申请记录
     * @param gid
     * @param cb
     */
    getApplyJoinGroup: function (gid, cb) {
        if (!this.applyJoin.hasOwnProperty(gid)) {
            cb(null, []);
            return;
        }
        var applyIds = this.applyJoin[gid];
        var applyInfo = [];
        for (var i = 0; i < applyIds.length; ++i) {
            gPlayerManger.getPlayer(applyIds[i], function (player) {
                if (!player) {
                    cb(Code.DB_ERROR);
                    return;
                }
                applyInfo.push(player);
            })
        }
        cb(null, applyInfo);
    },

    /***
     * 删除指定群组中的指定会员
     * @param gid
     * @param uid
     * @param cb
     */
    delMemberOfGroup: function (gid, uid, cb) {
        if (gid == uid) {
            cb(Code.NOT_DEL_GROUP);
            return;
        }
        if (this.groupMember.hasOwnProperty(gid)) {
            var groups = this.groupMember[gid];
            var delResult = this.removeByValue(groups, uid);
            gPlayerManger.getPlayer(uid, function (player) {
                var arr = player.user.groups;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] == gid) {
                        arr.splice(i, 1);
                    }
                }
                player.user.groups = arr;
                player.markDirty("groups");

                player.save(true);
                player.send("onDelMemberOfGroup", {"group": gid, "statusOfDel": true});

                if (!delResult) {
                    cb(Code.NOT_GROUP_MEMBER);
                    return;
                }
                cb();
            });
        }
    },

    delApply: function (gid, uid, cb) {
        if (!this.applyJoin.hasOwnProperty(gid)) {
            cb();
            return;
        }
        var applyIds = this.applyJoin[gid];
        var delResult = this.removeByValue(applyIds, uid);
        cb(null, {"delResult": delResult});
    },


    //==========================================
    //              功能函数
    //==========================================
    /***
     * 通过值删除数组中的指定元素
     * @param arr
     * @param val
     */
    removeByValue: function (arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                return true;
            }
        }
        return false;
    },

    /***
     * 数组中是否有指定值
     * @param arr
     * @param uid
     * @returns {boolean}
     */
    hasMember: function (arr, uid) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == uid) {
                return true;
            }
        }
        return false;
    }
}

exports.GroupManager = GroupManager;